<template>
  <div class="app-container">
    <!-- 筛选框 -->
    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="search_form.title"  placeholder="请输入标题" />
      </el-form-item>
      <el-form-item>
        <el-select v-model="search_form.hots" placeholder="请选择排序方式（热度）">
          <el-option label="降序" value= 1 />
          <el-option label="升序" value= 0 />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="search_form.status"  placeholder="请选择上架状态">
          <el-option label="全部" value="-1" />
          <el-option label="未上架" value="0" />
          <el-option label="已上架" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain class="el-icon-search" @click="search">查询</el-button>
        <el-button type="primary" plain class="el-icon-refresh" @click="reset">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right">
        <el-button
          type="primary"
          plain
          class="el-icon-plus"
          @click="showMask"
        >添加</el-button>
      </el-form-item>
    </el-form>

    <!-- 攻略列表 -->
    <div class="tableWrap">
      <el-table  v-loading="table_loading"  :data="tableData" border style="width: 100%">
        <!-- 排序 -->
        <el-table-column prop="sortWidget" label="排序" align="center" />
        <!-- 标题 -->
        <el-table-column prop="title" label="标题" align="center" />
        <!-- 浏览量 -->
        <el-table-column prop="hots" label="热度" align="center" />
        <!-- 发布人 -->
        <el-table-column  label="发布人" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.userId === null">管理员</span>
            <span v-if="scope.row.userId !== null">{scope.row.userId}</span>
          </template>
        </el-table-column>
        <!-- 上架状态 -->
        <el-table-column label="上架状态" align="center">
          <template slot-scope="scope">
            <div>
              <el-switch
                v-model="scope.row.status"
                active-text="上架"
                inactive-text="下架"
                :active-value="1"
                :inactive-value="0"
                @change="changeSwitch($event,scope.row)"
              />
            </div>
          </template>
        </el-table-column>
        <!-- 发布时间 -->
        <el-table-column prop="updateAt" label="创建时间" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.createAt | formatDate}}</span>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column
          label="操作"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="editArt(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="deleteArt(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <!-- 添加的页面 -->
    <add-talent
      v-if="showAddMask"
      :is-type="type"
      :is-hidden="showAddMask"
      :detail-info="detailInfo"
      :is-disabled="isDisabled"
      @checkMask="checkMask"
      @refresh="addOrUpdate"
    />
    <!-- 分页器 -->
    <div class="block">
      <el-pagination
        background
        :page-sizes="[10,20,50,100]"
        :page-size="pageSize"
        :pager-count="11"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

  </div>
</template>
<script>
  import { updateAd } from '../../api/adv'
  import { articleStatus, deleteArticle, getArticleList, getFaq } from '../../api/article'
  import addTalent from '../talent/add_talent'
  import { formatDate } from '../FormatDate/formateDate'
  import { appType } from '../../utils/constanst' // 添加组件
  export default {
    components: {
      addTalent
    },
    filters: {
      formatDate(time) {
        let date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd hh:mm')
      }
    },
    data() { // 数据声明初始
      return {
        search_form: {
          title:'',
          status: '',
          hots:null,
        }, // 筛选条件
        type: 3, // 3-问答
        showAddMask: false, // 是否显示添加弹窗
        page: 1,
        pageSize: 10,
        total: 0,
        tableData: [], // 列表数据
        detailInfo: {
        }, // 详细信息-修改
        isDisabled: false, // 默认允许是否编辑
        table_loading: false,
        model: 0// 0 初次加载   1表示条件筛选
      }
    },
    //新加路由保存参数
    beforeRouteLeave(to, from, next) {
      // const answer = window.confirm("当前页面搜索条件将会被保存");
      //更新 put
      let keyname = this.$route.name;
      let value = JSON.stringify(this.search_form);
      sessionStorage.setItem(keyname, value);
      next();
    },
    // 生命周期钩子，初始时获取数据
    mounted() {
      // 获取数据列表
      if (sessionStorage.getItem(this.$route.name)) {
        this.search_form = JSON.parse(sessionStorage.getItem(this.$route.name));
      }
      this.search()
    },
    methods: {
      // 筛选
      search() {
        this.model = 1
        this.getFaq({
          pageSize: this.pageSize,
          pageNum: this.page,
          articleType:this.type, //问答
          hots:this.search_form.hots ,
          status:this.search_form.status ==='' ? -1 :this.search_form.status,
          title:this.search_form.title,
        })
      },
      // 重置
      reset() {
        this.page = 1
        this.pageSize = 10
        this.search_form.title = ''
        this.search_form.status = ''
        this.search_form.hots = null
        this.getFaq()
      },
      // 获取数据列表
      getFaq(options = {
        pageSize: this.pageSize,
        pageNum: this.page,
        articleType:this.type, //问答
        hots:this.search_form.hots,
        status:this.search_form.status ==='' ? -1 :this.search_form.status,
      }) {
        this.table_loading = true
        getArticleList(options).then(res => {
          this.total = res.data.data.count
          this.pageNum = res.data.data.pageNum
          this.pageSize = res.data.data.pageSize
          this.tableData = res.data.data.list
          this.table_loading = false
        }).catch((error) => {
          this.table_loading = false
          this.$message.error('网络连接错误，请稍后再试')
        })
      },
      // 添加
      showMask() {
        this.detailInfo = {} // 详细信息初始为空
        this.showAddMask = true // 显示添加弹窗
      },
      // 删除
      deleteArt(id) {
        this.$confirm('确认删除该常见问题吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteArticle({
            id: id
          }).then((result) => {
            const res = result.data
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
             this.search()
            } else {
              this.$message.error(res.msg)
            }
          }).catch((err) => {
            this.$message.error('服务器网络错误，请稍后重试')
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 编辑
      editArt(row) {
        getFaq({
          id : row.id
        }).then(res => {
          this.detailInfo = res.data.data // 赋值
          this.isDisabled = false // 能否编辑
          this.showAddMask = true // 显示添加弹窗
        }).catch((error) => {
          this.table_loading = false
          this.$message.error('网络连接错误，请稍后再试')
        })
      },
      //添加或更新
      addOrUpdate(){
        this.search()
      },
      //关闭弹窗
      checkMask(isHidden) {
        this.detailInfo = {}
        this.showAddMask = isHidden
      },
      // 上架状态改变
      changeSwitch(status, item) {
        articleStatus( {
          id: item.id,
          status: status
        }).then(res => {
          if (res.data.code=== 0) {
            this.$message({
              message: '状态修改成功',
              type: 'success'
            })
          } else {
            this.$message.error(res.data.msg)
          }
          // 刷新列表
          this.search()
        }).catch(res => {
          this.$message.error('网络连接错误，请稍后再试')
        })
      },
      // 当前页面改变
      handleCurrentChange(val) {
        this.pageSize = val
        this.page = 1
        this.search()
      },
      // 条数改变
      handleSizeChange(page) {
        this.page = page
        this.search()
      }

    }
  }
</script>
<style scoped>
  label {
    font-size: 14px;
    font-weight: normal;
  }
  .smallBG {
    width: 100px;
    height: 100px;
  }
  .tableWrap {
    margin-top: 20px;
  }
  .block {
    background: #fff;
    padding: 32px 16px;
  }
</style>
